package com.spring.hot;

/**
 * @author Cizai
 * @since 2022/12/02 11:31
 **/
public class 删除链表的倒数第N个结点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {

        if (head == null) {
            return null;
        }
        if (head.next == null && n==1) {
            return null;
        }
        ListNode prev = new ListNode(-1);
        prev.next = head;

        ListNode last = head;
        ListNode slow = head;

        while (n>0 && last.next!=null) {
            last = last.next;
            n--;
        }

        while (last.next != null) {
            last = last.next;
            slow = slow.next;
        }

        slow.next = slow.next.next;

        return prev.next;

    }
}
